﻿namespace ChinaUnicom.Tasks
{
    using System;
    using ChinaUnicom.Models;
    using ChinaUnicom.Schedule;
    using System.Windows;

    internal class ClientTask : ITask
    {
        public Client Client { get; private set; }

        Context Context { get { return (Application.Current as App).Context; } }

        public ClientTask()
        {
            Client = new Client();
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.RequestUserInfo(x =>
            {
                if (x.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    ItemCollection items = Factory.Parser.Parse(x.Result, InfoType.Client);

                    foreach (var item in items)
                    {
                        if (item.Name.Equals("客户名称", System.StringComparison.OrdinalIgnoreCase))
                        {
                            Context.Account.ClientName = item.Value;
                            Client.Name = item.Value;
                        }
                        else if (!string.IsNullOrEmpty(item.Value))
                        {
                            Client.Items.Add(item);
                        }
                    }

                    if (Completed != null)
                    {
                        Completed(this, EventArgs.Empty);
                    }
                }
            });
        }

        public int Pending
        {
            get { return 10; }
        }

        public event EventHandler Completed;


        public event EventHandler Started;
    }
}
